﻿using AiBLSmartEdu.Module.SmartBiological.API.Services;
using FrameworkCore.Hubs;
using Microsoft.AspNetCore.SignalR;
using System.Collections.Concurrent;

namespace AiBLSmartEdu.Module.SmartBiological.API.Hubs;

#nullable disable

/// <summary>
/// 消息通知
/// </summary>
public class NotificationHub : Hub
{
    private static readonly ConcurrentDictionary<string, string> Users = new();

    private readonly BiologicalIssueServices _biologicalIssueServices;
    private readonly BiologicalIssueHelpers _biologicalIssueHelpers;

    public NotificationHub(BiologicalIssueServices biologicalIssueServices, BiologicalIssueHelpers chemistryAskHelpers)
    {
        _biologicalIssueServices = biologicalIssueServices;
        _biologicalIssueHelpers = chemistryAskHelpers;
    }

    /// <summary>
    /// 接收问题并发送答案
    /// </summary>
    /// <param name="issue">要发送的问题</param>
    public virtual async Task SendBiologicalIssueMessage(string issue)
    {
        string answer = await _biologicalIssueServices.GetAnswerByQuestionAsync(issue);
        if (string.IsNullOrWhiteSpace(answer))
        {
            string answerXml = await _biologicalIssueHelpers.FetchAnswerAsync(issue);
            answer = await _biologicalIssueHelpers.ConvertXmlToHtmlAsync(answerXml);
            await _biologicalIssueServices.UpdateAnswerAsync(GetUserId(), issue, answer);
        }

        await Clients.Caller.SendAsync("ReceiveBiologicalIssueMessage", answer);
    }

    /// <summary>
    /// 客户端连接时的逻辑。
    /// </summary>
    public override async Task OnConnectedAsync()
    {
        Users.TryAdd(Context.GetAccessToken(), Context.GetUserId());

        await base.OnConnectedAsync();
    }

    /// <summary>
    /// 获取用户链接Id
    /// </summary>
    /// <returns></returns>
    private string GetUserId()
    {
        Users.TryGetValue(Context.GetAccessToken(), out string? userId);
        return userId;
    }
}